/**
 * Created by cchen on 2015/6/2.
 */

var toolUtil = require('../common/utils/toolUtil');
var mysqlUtil = require('../common/utils/mysqlUtil');
var async = require('async');
var Community = mongoose.model('community');
var Users = mongoose.model('user');
var moment = require('moment');
var inviteRecord = mongoose.model('invite_score_record');


exports.getLotteryDetailService = function (userId, lotteryId, callback) {
    var totalNum;
    async.series([
        function (callbackInner) {
            Users.findOne({_id: userId}).populate('community', 'communityName')
                .exec(function (err, result) {
                    var data = {
                        communityName: result.community.communityName,
                        isAuth: result.authenticationStatus
                    };
                    callbackInner(err, data)
                })
        },
        function (callbackInner) {
            var sql = 'SELECT * FROM lottery_activity WHERE id=?';
            mysqlUtil.query(sql, [lotteryId], function (err, result) {
                var data = {
                    name: result[0].activity_name,
                    desc: result[0].activity_desc,
                    startTime: result[0].begin_time,
                    endTime: result[0].end_time,
                    totalNum: result[0].lottery_limit
                };
                totalNum = result[0].lottery_limit;
                callbackInner(err, data);
            })
        },
        function (callbackInner) {
            var ts = moment().startOf("day").toDate().getTime();

            var sql = 'SELECT COUNT(*) as count FROM lottery_log WHERE user_id=? and create_time>' + ts;
            logger.info(sql)
            mysqlUtil.query(sql, [userId], function (err, result) {
                callbackInner(err, totalNum - result[0].count)
            })
            //var key = 'lottery:user:count:' + moment().format('YYYYMMDD') + ':' + userId;
            //
            //redisClient.get(key, function (err, count) {
            //    count = count == null ? 0 : Number(count);
            //    callbackInner(null, totalNum - count);
            //})
        },
        function (callbackInner) {
            Users.findOne({_id: userId}, function (err, user) {
                var sql = 'SELECT * FROM lottery_prize p,lottery_award a WHERE p.lottery_id=? AND a.lottery_id=? AND a.prize_id=p.id and a.community_id=? AND p.prize_level=1';
                mysqlUtil.query(sql, [lotteryId, lotteryId, user.community + ''], function (err, result) {
                    if (result != null && result.length > 0) {
                        callbackInner(null, true);
                    } else {
                        callbackInner(null, false);
                    }
                });
            })
        },
        function (callbackInner) {
            var ts = moment().startOf("day").toDate().getTime();
            var sql = 'SELECT * FROM lottery_award WHERE user_id=? and create_time>' + ts;
            mysqlUtil.query(sql, [userId], function (err, result) {
                if (result != null && result.length > 0) {
                    callbackInner(null, true);
                } else {
                    callbackInner(null, false);
                }
            });
        }
    ], callback);
};

exports.generateLotteryTicketService = function (userId, lotteryId, callback) {
    var num = exports.getRandomNumber();
    var community;
    var name;

    var ts = moment().startOf("day").toDate().getTime();

    //var key = 'lottery:user:count:' + moment().format('YYYYMMDD') + ':' + userId;
    //
    //redisClient.get(key, function (err, result) {
    //    result = result == null ? 0 : Number(result);
    var sql = 'SELECT COUNT(*) as count FROM lottery_log WHERE user_id=? and create_time>' + ts;
    mysqlUtil.query(sql, [userId], function (err, result) {

        mysqlUtil.query('SELECT * from lottery_activity WHERE id=?', [lotteryId], function (err, activity) {

            if (activity[0].begin_time > new Date().getTime()) {
                callback({message: '活动尚未开始'})
            } else if (activity[0].end_time < new Date().getTime()) {
                callback({message: '活动已结束'})
            } else {

                name = activity[0].activity_name;
                if (activity[0].lottery_limit - result[0].count > 0) {
                    var now = new Date();
                    var key = 'lottery:666:' + moment().format('YYYYMMDD');
                    redisClient.get(key, function (err, value) {
                        if (value != null) {
                            num = exports.getRandomNumber();
                        }
                        async.series([
                            function (callbackInner) {
                                Users.findOne({_id: userId}, function (err, result) {
                                    community = result.community + '';
                                    callbackInner(err, num);
                                })
                            },
                            function (callbackInner) {

                                var luckyNum = num.match(/6/g) == null ? 0 : num.match(/6/g).length;

                                var level;
                                if (luckyNum == 3) {
                                    redisClient.set(key, "1");
                                    level = 1;
                                } else if (luckyNum == 2) {
                                    level = 2;
                                } else if (luckyNum == 1) {
                                    level = 3;
                                }

                                if (level != null) {
                                    var sql = 'SELECT * FROM lottery_product d,lottery_prize p WHERE p.lottery_id=? AND p.prize_level=' + level + ' AND p.product_id = d.id'

                                    mysqlUtil.query(sql, [lotteryId], function (err, result) {
                                        if (result != null && result.length > 0) {

                                            var input = {
                                                lottery_id: lotteryId,
                                                user_id: userId,
                                                prize_id: result[0].id,
                                                community_id: community,
                                                award_num: num,
                                                create_time: new Date().getTime()
                                            };
                                            mysqlUtil.query('insert into lottery_award set?', input, function (err, data) {
                                                callbackInner(err, result[0].name);
                                                logger.info(result);
                                                exports.giveUserAwardsService(userId, result[0].type, result[0].reward_count, name + result[0].level_name)
                                            })
                                        } else {
                                            callbackInner({message: '无奖品信息'})
                                        }
                                    })
                                } else {
                                    callbackInner();
                                }

                                //
                                //if (num == '666') {
                                //    var sql = 'SELECT * FROM lottery_prize p,lottery_award a WHERE p.lottery_id=? AND a.lottery_id=? AND a.prize_id=p.id and a.community_id=? AND p.prize_level=1';
                                //    mysqlUtil.query(sql, [lotteryId, lotteryId, community], function (err, result) {
                                //        var sql2;
                                //        if (result != null && result.length > 0 && result.length >= result[0].prize_count) {
                                //            sql2 = 'SELECT * FROM lottery_product d,lottery_prize p WHERE p.lottery_id=? AND p.prize_level=2 AND p.product_id = d.id'
                                //        } else {
                                //            sql2 = 'SELECT * FROM lottery_product d,lottery_prize p WHERE p.lottery_id=? AND p.prize_level=1 AND p.product_id = d.id'
                                //        }
                                //        mysqlUtil.query(sql2, [lotteryId], function (err, result) {
                                //            if (result != null && result.length > 0) {
                                //
                                //                var sql3 = 'SELECT COUNT(*) as count FROM lottery_award WHERE prize_id =? and community_id=?';
                                //
                                //                mysqlUtil.query(sql3, [result[0].id, community], function (err, count) {
                                //                    if (result[0].prize_count != -1 && count[0].count >= result[0].prize_count) {
                                //                        callbackInner({message: '无中奖次数'})
                                //                    } else {
                                //                        var input = {
                                //                            lottery_id: lotteryId,
                                //                            user_id: userId,
                                //                            prize_id: result[0].id,
                                //                            community_id: community,
                                //                            award_num: num,
                                //                            create_time: new Date().getTime()
                                //                        };
                                //                        mysqlUtil.query('insert into lottery_award set?', input, function (err, data) {
                                //                            callbackInner(err, result[0].name);
                                //                            logger.info(result);
                                //                            exports.giveUserAwardsService(userId, result[0].type, result[0].reward_count, name + result[0].level_name)
                                //                        })
                                //                    }
                                //                })
                                //            } else {
                                //                callbackInner({message: '无奖品信息'})
                                //            }
                                //        })
                                //    })
                                //} else {
                                //    if (num != '000' && Number(num) % 6 == 0) {
                                //        mysqlUtil.query('SELECT * FROM lottery_product d,lottery_prize p WHERE p.lottery_id=? AND p.prize_level=3 AND p.product_id = d.id', [lotteryId], function (err, result) {
                                //            if (result != null && result.length > 0) {
                                //                logger.info(result);
                                //                var sql3 = 'SELECT COUNT(*) as count FROM lottery_award WHERE prize_id =? and community_id=?';
                                //
                                //                mysqlUtil.query(sql3, [result[0].id, community], function (err, count) {
                                //                    if (result[0].prize_count != -1 && count[0].count >= result[0].prize_count) {
                                //                        callbackInner({message: '无中奖次数'})
                                //                    } else {
                                //                        var input = {
                                //                            lottery_id: lotteryId,
                                //                            user_id: userId,
                                //                            prize_id: result[0].id,
                                //                            community_id: community,
                                //                            award_num: num,
                                //                            create_time: new Date().getTime()
                                //                        };
                                //                        mysqlUtil.query('insert into lottery_award set?', input, function (err, data) {
                                //                            callbackInner(err, result[0].name);
                                //                            exports.giveUserAwardsService(userId, result[0].type, result[0].reward_count, name + result[0].level_name)
                                //                        });
                                //                    }
                                //                });
                                //            } else {
                                //                callbackInner({message: '无奖品信息'})
                                //            }
                                //        })
                                //    } else {
                                //        callbackInner();
                                //    }
                                //}
                            },
                            function (callbackInner) {
                                var input = {
                                    lottery_id: lotteryId,
                                    user_id: userId,
                                    award_num: num,
                                    create_time: new Date().getTime()
                                };

                                if (num.match(/6/g) != null) {
                                    input.is_winning = 1
                                } else {
                                    input.is_winning = 0
                                }
                                mysqlUtil.query('insert into lottery_log set?', input, callbackInner)
                            }
                        ], callback)
                    });
                } else {
                    var msg = {
                        message: '抽奖次数已经用完'
                    };
                    callback(msg, null)
                }
            }
        });
    });
};

exports.getRandomNumber = function () {
    var Num = '';
    for (var j = 0; j < 3; j++) {
        Num += Math.floor(Math.random() * 10);
    }
    return Num;
};


exports.getLotteryAwardListService = function (userId, lotteryId, page, callback) {

    var format = '?imageView2/2/format/jpg';

    var start = new Date().getTime();
    var offset = (Number(page) - 1) * 10;
    Users.findOne({_id: userId}, function (err, result) {
        var community = result.community + '';
        var date2 = new Date().getTime() - start;
        var data = [];

        var sql = 'SELECT * from lottery_product d,lottery_prize p,lottery_award a WHERE a.prize_id = p.id and p.product_id = d.id and a.community_id=? and a.lottery_id=? ORDER BY prize_level,a.create_time DESC  limit ' + offset + ' ,10';
        mysqlUtil.query(sql, [community, lotteryId], function (err, result) {

            var date3 = new Date().getTime() - start;

            if (result != null) {
                async.eachSeries(result, function (award, callbackInner) {
                    Users.findOne({_id: award.user_id}, 'nickName images roomUnit', function (err, user) {

                        var temp = {
                            nickName: user.nickName,
                            roomUnit: user.roomUnit,
                            images: user.images[0].imageURL.indexOf('http') == 0 ? user.images[0].imageURL : imgHost + user.images[0].imageURL + format,
                            time: award.create_time,
                            awardNum: award.award_num,
                            prize: award.name
                        };
                        data.push(temp);
                        callbackInner();
                    })
                }, function (err) {

                    var date4 = new Date().getTime() - start;

                    callback(err, data);
                })
            } else {
                callback(null, data);
            }
        })
    })
};


exports.giveUserAwardsService = function (userId, type, count, reason) {
    if (type == 2) {    //加情值奖励
        var input = {
            userId: userId + '',
            userRole: 1,
            addScore: count,
            addScoreReason: reason,
            userActionType: 22
        };

        input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

        scoreProxy.invoke('addScore', [input], function (err, result) {
            if (err) {
                logger.error('Exception happened when addScoreManual ...!' + err.message);
            } else {
                var data = JSON.parse(decodeURIComponent(result));
                logger.info(data);
            }
        });
    }
};


//====================1.7.0新版老虎机=======================

exports.getLotteryDetailNewService = function (userId, lotteryId, callback) {
    var format = '?imageView2/2/format/jpg';
    var totalNum;
    async.series([
        function (callbackInner) {
            Users.findOne({_id: userId}).populate('community', 'communityName')
                .exec(function (err, result) {
                    var data = {
                        communityName: result.community.communityName,
                        isAuth: result.authenticationStatus
                    };
                    callbackInner(err, data)
                })
        },
        function (callbackInner) {
            var sql = 'SELECT * FROM lottery_activity WHERE id=?';
            mysqlUtil.query(sql, [lotteryId], function (err, result) {
                if (result == null || result.length == 0) {
                    callbackInner({message: '活动不存在或已被删除'})
                } else {
                    var data = {
                        name: result[0].activity_name,
                        desc: result[0].activity_desc,
                        startTime: result[0].begin_time,
                        endTime: result[0].end_time,
                        totalNum: result[0].lottery_limit
                    };
                    totalNum = result[0].lottery_limit;
                    callbackInner(err, data);
                }
            })
        },
        function (callbackInner) {
            var key = 'lottery:' + moment().format('YYYYMMDD') + ':' + lotteryId + ':userCount:' + userId;

            redisClient.get(key, function (err, count) {
                count = count == null ? 0 : Number(count);
                callbackInner(null, totalNum - count);
            })
        },
        function (callbackInner) {
            var sql = 'select * from lottery_prize p,lottery_product d where p.lottery_id =? and p.product_id=d.id';
            mysqlUtil.query(sql, [lotteryId], function (err, result) {
                var prizeList = [];

                if (result != null && result.length > 0) {
                    result.forEach(function (temp) {
                        var prize = {
                            position: temp.prize_position,
                            name: temp.name,
                            pic: temp.prize_pic.indexOf('http') == 0 ? temp.prize_pic : imgHost + temp.prize_pic + format
                        };
                        prizeList.push(prize);
                    })
                }

                prizeList.sort(function (a, b) {
                    return a.position - b.position;
                });
                callbackInner(null, prizeList);
            })
        }
    ], callback);
};

exports.userLotteryDrawService = function (userId, lotteryId, callback) {
    mysqlUtil.query('select * from lottery_activity where id=?', [lotteryId], function (err, activity) {

        if (activity == null || activity.length == 0) {
            callback({message: '活动不存在'})
        } else {
            var now = new Date().getTime();
            if (activity[0].begin_time > now || activity[0].end_time < now) {
                callback({message: '活动尚未开始或已结束'})
            } else {
                var limit = activity[0].lottery_limit;

                var key = 'lottery:' + moment().format('YYYYMMDD') + ':' + lotteryId + ':userCount:' + userId;

                redisClient.get(key, function (err, count) {
                    if (Number(count) < limit) {
                        var sql = 'select p.*,d.type from lottery_prize p,lottery_product d where p.product_id=d.id and p.lottery_id=?';
                        mysqlUtil.query(sql, [lotteryId], function (err, result) {
                            if (result != null && result.length > 0) {
                                var prizeList = new Array(result.length);
                                var sum = 0;
                                result.forEach(function (temp) {
                                    prizeList[temp.prize_position] = temp;

                                    sum += temp.prize_probability;
                                });

                                if (sum < 0.9 || sum > 1.1) {
                                    callback({message: '概率错误'})
                                } else {
                                    var perKey = 'lottery:' + moment().format('YYYYMMDD') + ':' + lotteryId + ':userPer:' + userId;

                                    exports.getLotteryResult(prizeList, lotteryId, perKey, function (err, result) {

                                        redisClient.INCRBY(key, 1, function (err, value) {
                                            if (result.prize.reward_count != 0) {
                                                redisClient.INCRBY(perKey, 1)
                                            }
                                        });
                                        redisClient.EXPIRE(key, 86400);

                                        if (result.prize.reward_count != 0) {
                                            exports.giveUserAwardsService(userId, result.prize.type, result.prize.reward_count, '天天抽獎');

                                            Users.findOne({_id: userId}, 'community').populate('community', '_id').exec(function (err, user) {
                                                var input = {
                                                    lottery_id: lotteryId,
                                                    user_id: userId,
                                                    prize_id: result.prize.id,
                                                    community_id: user.community._id + '',
                                                    create_time: new Date().getTime()
                                                };
                                                mysqlUtil.query('insert into lottery_award set?', input, function (err, data) {
                                                })
                                            })
                                        }

                                        var input = {
                                            lottery_id: lotteryId,
                                            user_id: userId,
                                            create_time: new Date().getTime()
                                        };

                                        if (result.prize.reward_count != 0) {
                                            input.is_winning = 1
                                        } else {
                                            input.is_winning = 0
                                        }
                                        mysqlUtil.query('insert into lottery_log set?', input, function (err, data) {
                                        });


                                        callback(null, {
                                            position: result.position,
                                            isLucky: result.prize.reward_count != 0
                                        });
                                    });
                                }
                            } else {
                                callback({message: '无此活动，或无奖品信息'})
                            }
                        })

                    } else {
                        callback({message: '无抽奖次数'})
                    }
                })
            }
        }
    })
};

exports.getAroundCommunity = function (communityId, callback) {
    Community.findOne({_id: communityId}, 'groups', function (err, result) {
        var data = [];
        data.push(communityId);

        if (result.groups != null && result.groups.length > 0) {
            Community.find({groups: result.groups, _id: {$ne: communityId}})
                .exec(function (err, value) {
                    value.forEach(function (temp) {
                        data.push(temp._id + '');
                    });
                    callback(null, data);
                })
        } else {
            callback(null, data);
        }
    });
};

exports.getLuckyUsersService = function (userId, lotteryId, page, callback) {
    var format = '?imageView2/2/w/75/h/75/format/jpg';

    var offset = (Number(page) - 1) * listPageSize;
    Users.findOne({_id: userId}, function (err, result) {
        var community = result.community + '';

        exports.getAroundCommunity(community, function (err, communityList) {
            var sql = 'SELECT * from lottery_product d,lottery_prize p,lottery_award a WHERE a.prize_id = p.id and p.product_id = d.id and a.lottery_id=? and (';

            for (var i = 0; i < communityList.length; i++) {
                if (i == communityList.length - 1) {
                    sql += 'a.community_id="' + communityList[i] + '") '
                } else {
                    sql += 'a.community_id="' + communityList[i] + '" or ';
                }
            }
            sql += 'ORDER BY a.create_time DESC  limit ' + offset + ' ,' + listPageSize;

            var data = [];

            mysqlUtil.query(sql, [lotteryId], function (err, result) {

                if (result != null) {
                    async.eachSeries(result, function (award, callbackInner) {
                        Users.findOne({_id: award.user_id}, 'nickName community images roomUnit showUnit gender', function (err, user) {

                            var temp = {
                                nickName: user.nickName,
                                community: user.community.communityName,
                                roomUnit: !isNaN(user.roomUnit) ? user.roomUnit + '单元' : user.roomUnit,
                                gender: user.gender,
                                images: user.images[0].imageURL.indexOf('http') == 0 ? user.images[0].imageURL : imgHost + user.images[0].imageURL + format,
                                time: award.create_time,
                                prize: award.name
                            };

                            if (temp.roomUnit == null) {
                                temp.roomUnit = '';
                            }

                            if (!user.showUnit) {
                                temp.roomUnit = '';
                            }

                            data.push(temp);
                            callbackInner();
                        }).populate('community', 'communityName')
                    }, function (err) {

                        callback(err, data);
                    })
                } else {
                    callback(null, data);
                }
            })
        });
    })
};

exports.getMyLuckyRecordService = function (userId, lotteryId, page, callback) {
    var offset = (Number(page) - 1) * listPageSize;

    var sql = 'SELECT * from lottery_product d,lottery_prize p,lottery_award a WHERE a.prize_id = p.id and p.product_id = d.id and a.user_id=? and a.lottery_id=? ORDER BY a.create_time DESC  limit ' + offset + ' ,' + listPageSize;
    var data = [];
    mysqlUtil.query(sql, [userId, lotteryId], function (err, result) {

        if (result != null) {
            result.forEach(function (award) {
                var temp = {
                    time: award.create_time,
                    prize: award.name
                };
                data.push(temp);
            })
        }
        callback(null, data);
    })
}


var lotteryCount = 0;

/**
 * 获取抽奖结果
 * @param prizeList
 * @param lotteryId
 * @param perKey
 * @param callback
 */
exports.getLotteryResult = function (prizeList, lotteryId, perKey, callback) {

    lotteryCount++;

    redisClient.get(perKey, function (err, per) {
        var pdf = new Array(prizeList.length);

        var perFlag = true;
        prizeList.forEach(function (prize) {
            if (per != null) {
                var p = per == '1' ? 0.5 : 0.2;
                pdf[prize.prize_position] = prize.prize_probability * p;

                if (prize.reward_count == 0 && perFlag) {
                    pdf[prize.prize_position] += 1 - p;
                    perFlag = false;
                }
            } else {
                pdf[prize.prize_position] = prize.prize_probability;
            }
        });


        var cdf = pdf.slice();

        for (var i = 1; i < cdf.length - 1; i++)
            cdf[i] += cdf[i - 1];

        cdf[cdf.length - 1] = 1;

        var x = Math.random();


        var num = -1;

        var flag = false;

        async.eachSeries(cdf, function (value, callbackInner) {

            var i = cdf.indexOf(value);

            if (x < value && !flag) {
                flag = true;
                var limit = prizeList[i].prize_count;

                if (limit == -1) {
                    num = i;
                    callbackInner();
                } else {
                    var key = 'lottery:' + moment().format('YYYYMMDD') + ':' + lotteryId + ':position:' + i;

                    redisClient.get(key, function (err, count) {
                        count = count == null ? 0 : Number(count);
                        if (limit > count) {

                            redisClient.INCRBY(key, 1);
                            redisClient.EXPIRE(key, 86400);
                            num = i;
                        }
                        callbackInner();
                    })
                }
            } else {
                callbackInner();
            }
        }, function () {
            if (lotteryCount < prizeList.length + 1) {
                if (num == -1) {
                    exports.getLotteryResult(prizeList, lotteryId, callback)
                } else {
                    lotteryCount = 0;
                    callback(null, {position: num, prize: prizeList[num]});
                }
            } else {

                lotteryCount = 0;

                var position = 0;

                for (var n = 0; n < prizeList.length; n++) {
                    if (prizeList[n].reward_count == 0) {
                        position = n;
                        break;
                    }
                }

                callback(null, {position: position, prize: prizeList[position]});
            }
        })
    });
};
